package com.woniuxy.service.impl;

public class JmmCodeReorder {
    private volatile static int x = 0, y = 0;
    private volatile static int a = 0, b = 0;
    public static void main(String[] args) throws InterruptedException {
        int i = 0;
        for (; ; ) {
            i++;
            x = 0;
            y = 0;
            a = 0;
            b = 0;

            Thread t1 = new Thread(new Runnable() {
                public void run() {
                    shortWait(10000);
                    a = 1; //写a;StoreLoad;读b
                    x = b; //读b
                }
            });
            //a b x y ：1 1 1 1  t1和t2线程同时执行
            //a b x y ：1 1 0 1  t1线程先执行
            //a b x y ：1 1 1 0  t2线程先执行
            //a b x y ：0 0 0 0  有没有这种情况？

            Thread t2 = new Thread(new Runnable() {
                public void run() {
                    b = 1; //写b;StoreLoad;读b
                    y = a; //读a
                }
            });
            t1.start();
            t2.start();
            t1.join();
            t2.join();
            String result = "第" + i + "次 (" + x + "," + y + "）";
//            System.out.println(result);
            if (x == 0 && y == 0) {//如果指令是顺序执行，那么这个判断永远不可能为true
                System.out.println(result);
                break;
            }else if (x == 1 && y == 1)  {
                System.out.println(result);
            }
        }
    }


    /** * 等待一段时间，时间单位纳秒 * @param interval */
    public static void shortWait(long interval) {
        long start = System.nanoTime();
        long end;

        do {
            end = System.nanoTime();
        } while (start + interval >= end);
    }
}
